<?php

include_once(dirname(__FILE__)."/AController.php");

class PaymentController extends AController {
	
	/**
	 * 查看付款请求
	 */
	public function actionRequest() {
		$arr = array(
			'pagination' => array('pageSize' => 30),
			'criteria' => array(
				'order' => 'payment_request_id DESC',
				'condition' => 'status=0'
			)
		);
		$dataProvider = new CActiveDataProvider("PaymentRequest", $arr);
		$this->render('request', array('dataProvider' => $dataProvider, 'block_title' => '付款请求'));
	}
	
	public function actionMarkRequest() {
		if (!empty($_POST['requests'])) {
			foreach ($_POST['requests'] as $id) {
				$paymentRequest = PaymentRequest::model()->findByPk($id);
				
				$payment = new Payment();
				$payment->adddate = date('Y-m-d H:i:s');
				$payment->amount = $paymentRequest->amount;
				$payment->payment_request_id = $paymentRequest->payment_request_id;
				$payment->owner_id = $paymentRequest->owner_id;
				$payment->save();
				
				$paymentRequest->markStatus(2, 1, $payment->payment_id);
				$paymentRequest->status = 1;
				$paymentRequest->save();
			}
		}
		$this->redirect(array('payment/request')); 
	}
	
	/**
	 * 查看佣金支付历史
	 */
	public function actionHistory() {
		$arr = array(
			'criteria' => array('order' => 'id DESC')
		);
		$dataProvider = new CActiveDataProvider('Payment', $arr);
		$this->render('history', array('dataProvider' => $dataProvider));
	}
	
	/**
	 * 查看月结待付款报表清单
	 * 如果到了月结日，则自动生成一个报表
	 */
	public function actionMonthReportList() {
		$arr = array(
			'pagination' => array('pageSize' => 30),
		);
		$countSql = "SELECT count(*) FROM month_report GROUP BY month";
		$arr['totalItemCount'] = Yii::app()->db->createCommand($countSql)->queryScalar();
		$sql = "SELECT
					year(month) year,
					month(month) month,
					sum(joinmb) joinmb,
					sum(firstordernum) firstordernum,
					sum(firstorderamount) firstorderamount,
					sum(total_earn) total_earn,
					count(*) owner_count
				FROM month_report
				GROUP BY month
				ORDER BY month DESC";
		$dataProvider = new QpidSqlDataProvider($sql, $arr);
		$this->render('monthReportList', array('dataProvider' => $dataProvider));
	}
	
	/**
	 * 查看某个月的报表明细
	 * @param string $month
	 */
	public function actionMonthReportDetail($month) {
		$month .= '-01';
		$arr = array(
			'pagination' => array('pageSize' => 30),
			'criteria' => array(
				'condition' => "month='{$month}'",
				'order' => 'month_report_id DESC'
			)
		);
		$dataProvider = new CActiveDataProvider('MonthReport', $arr);
		$this->render('monthReportDetail', array('dataProvider' => $dataProvider));
	}
	
	/**
	 * 应付统计
	 */
	public function actionToPayList() {
		$arr = array(
			'pagination' => array('pageSize' => 30),
			'criteria' => array(
				'condition' => 'balance>'.Yii::app()->params['minBalanceForPay']
			)
		);
		$dataProvider = new CActiveDataProvider('Owner', $arr);
		$this->render('toPayList', array('dataProvider' => $dataProvider));
	}
	
	/**
	 * 选择为哪些注册会员支付
	 */
	public function actionSelectMonths($owner_id) {
		$arr = array(
			'criteria' => array(
				'condition' => "owner_id='$owner_id' AND payment_status=0",
				'order' => 'month DESC'
			),
		);
		$dataProvider = new CActiveDataProvider('MonthReport', $arr);
		$this->render('selectMonths', array('dataProvider' => $dataProvider, 'owner_id' => $owner_id));
	}
	
	/**
	 * 填写支付信息
	 */
	public function actionPayForMonth() {
		$owner = Owner::model()->find('loginid=:id', array(':id' => $_GET['owner_id']));
		if ($_GET['step'] == 1) {//显示支付信息填写表单
			if (empty($_POST['months'])) {
				throw new CHttpException('', '请选择月份');
			}
			$monthList = Yii::app()->db->createCommand()
						->select('*')
						->from('month_report')
						->where(array('and', "owner_id='{$_GET[owner_id]}'"), array('in', 'month', $_POST['months']))
						->queryAll();
			$remark = "";
			$amount = 0;
			$months = array();
			foreach($monthList as $month) {
				$months[] = $month;
				$remark .= date('Y-m', strtotime($month['month'])) ."(\$".$month['total_earn'] .")\r\n";
				$amount += $month['total_earn'];
			}
			sess('payMonths', $months);
			$data['owner'] = $owner;
			$data['amount'] = $amount;
			$data['remark'] = $remark;
			$data['actionUrl'] = $this->createUrl("payment/payForMonth", array("owner_id" => $owner->loginid, "step" => 2));
			$this->render('create', $data);
		} else if ($_GET['step'] == 2) {//保存支付信息
			$data = $_POST['Payment'];
			$data['adddate'] = date('Y-m-d H:i:s');
			$data['pay_date'] = date("Y-m-d", strtotime("{$_POST['year']}-{$_POST['month']}-{$_POST['day']}"));
			$data['ip'] = CHttpRequest::getUserHostAddress();
			$data['usertype'] = $owner->usertype;
			
			$data['memberlist'] = '0';
			$data['orderlist'] = '0';
			
			$trans = Yii::app()->db->beginTransaction();
			try {
				$payment = new Payment();
				$payment->attributes = $data;
				$payment->save();
				
				//加盟账户里余额减少,已付款增加
				$owner->balance -= $payment->amount;
				$owner->paid_amount += $payment->amount;
				$owner->save();
				
				//如果该加盟账户有发送过付款请求，则将此付款请求标记为已付款
				PaymentRequest::model()->updateAll(array('status' => 1), 'owner_id=:owner_id AND status=0', array(':owner_id' => $owner->owner_id));
				
				$orderListString = "";
				$userListString = "";
				foreach (sess('payMonths') as $mon) {
					list($y, $m, $d) = explode('-', $mon);
					
					//在报表明细表，记录此次付款涉及的注册会员和订单
					$orderCond = "f.order_id=h.order_id AND owner_id='{$owner->loginid}'
							      AND year(verifydate)=$y AND month(verifydate)=$m AND verify_status=1";
					$sql = "SELECT f.order_id FROM first_order f, order_history h WHERE $orderCond";
					$orderList = Yii::app()->db->createCommand($sql)->queryAll();
					foreach ($orderList as $order) {
						$orderListString .= $order['order_id'].',';
					}
					$orderListString = trim($orderListString, ',');

					$userCond = "owner_id='{$owner->loginid}' AND year(date_join)=$y AND month(date_join)=$m AND accept='Y'";					
					$userList = User::model()->findAll($userCond);
					foreach ($userList as $user) {
						$userListString .= $user['user_id'].',';
					}
					$userListString = trim($userListString, ',');
					
					//将此次支付涉及到的首次订单、注册会员的付款状标记为已付款
					$sql = "UPDATE first_order f,order_history h SET payment_status=1, payment_id={$payment->id} WHERE $orderCond";
					Yii::app()->db->createCommand($sql)->execute();
					Yii::app()->db->createCommand()->update('user', array('payment_status' => 1, 'payment_id' => $payment->id), $userCond);
					
					$monthReport = MonthReport::model()->find("owner_id='{$owner->loginid}' AND month='$mon'");
					$monthReport->payment_status = 1;
					$monthReport->save();
				} 
				
				$payment->memberlist = $userListString;
				$payment->orderlist = $orderListString;
				$payment->save();
				
				$trans->commit();
			} catch (Exception $e) {
				$trans->rollback();
			}
			
			$this->redirect(array('payment/toPayList'));
			
		} else {
			return false;
		}	
	}
	
	/**
	 * 处理付款请求
	 */
	public function actionPayForRequest() {
		$owner = Owner::model()->find('loginid=:id', array(':id' => $_GET['owner_id']));
		if (empty($_POST)) {
			sess('payRequestId', $_GET['request_id']);
			$data = array();
			$result =  QpidBalance::activeCount($_GET['owner_id']);
			$data['amount'] = $result['balance'];
			$data['owner'] = $owner;
			$data['remark'] = '-';
			$data['actionUrl'] = $this->createUrl("payment/payForRequest", array("owner_id" => $_GET['owner_id']));
			$this->render('create', $data);
		} else {
			//增加一条付款记录
			$trans = Yii::app()->db->beginTransaction();
			try {
				$payment = new Payment();
				$payment = new Payment();
				$payment->attributes = $_POST['Payment'];
				$payment->save();
				
				//将付款请求的付款状态标记为 1
				PaymentRequest::model()->updateAll(array('status' => 1), 'payment_request_id='.sess('payRequestId'));
				
				//将涉及到的订单列表、会员列表写进付款记录表
				$orderListString = "";
				$userListString = "";
				$orderCond = "f.order_id=h.order_id AND owner_id='{$owner->loginid}' AND verify_status=1 AND payment_status=0";
				$sql = "SELECT f.order_id FROM first_order f, order_history h WHERE $orderCond";
				$orderList = Yii::app()->db->createCommand($sql)->queryAll();
				foreach ($orderList as $order) {
					$orderListString .= $order['order_id'].',';
				}
				$orderListString = trim($orderListString, ',');
			
				$userCond = "owner_id='{$owner->loginid}' AND accept='Y' AND payment_status=0";
				$userList = User::model()->findAll($userCond);
				foreach ($userList as $user) {
					$userListString .= $user['user_id'].',';
				}
				$userListString = trim($userListString, ',');
				$payment->memberlist = $userListString;
				$payment->orderlist = $orderListString;
				$payment->save();
				
				//将涉及到的首次订单、注册会员付款状态标记为 1
				$sql = "UPDATE first_order f,order_history h SET payment_status=1, payment_id={$payment->id} WHERE $orderCond";
				Yii::app()->db->createCommand($sql)->execute();
				Yii::app()->db->createCommand()->update('user', array('payment_status' => 1, 'payment_id' => $payment->id), $userCond);
				
				//将报表里的付款状态标记为 1（假如有报表的话）
				$params = array(':owner_id' => $owner->loginid);
				$cond = 'owner_id=:owner_id AND payment_status=0';
				MonthReport::model()->updateAll(array('payment_status' => 1), $cond, $params);
				
				//将加盟账户里的余额设为 0,已付款增加
				$owner->balance = 0;
				$owner->paid_amount += $payment->amount;
				$owner->save();
				
				$trans->commit();
			} catch (Exception $e) {
				$trans->rollback();
			}
			$this->redirect(array('payment/request'));
		}
	}
	
	/**
	 * 生成月待付报表
	 * 计算截至当月，应该付多少佣金给加盟账号
	 * @param int $year
	 * @param int $month
	 */
	public function actionGenerateMonthReport() {
		if (empty($_GET['month'])) {
			if (Yii::app()->params['paymentMonthly'] > date('d')) {
				$month = date('Y-m', strtotime("$month -1 months"));	
			}
			$this->render('generateMonthReport', array('month' => $month));
		} elseif (0 && $_GET['year'].'-'.$_GET['month'] >= date('Y-m')) {
			throw new CHttpException('', '当月只能生成往月的报表');
			return false;
		} elseif (MonthReport::model()->count("month=:month", array(':month' => $_GET['year'].'-'.$_GET['month'].'-01'))) {
			throw new CHttpException('', '报表已经存在，不能重复生成');
			return false;
			//$this->redirect(array('payment/monthReportDetail', 'month' => $_GET['year'].'-'.$_GET['month']));
		} else {
			set_time_limit(0); //避免超时
			$curMonth = $_GET['year'] .'-'. $_GET['month'] .'-01';
			$nextMonth = date('Y-m-01', strtotime("$curMonth +1 months"));
			$data = array();
			
			$trans = Yii::app()->db->beginTransaction();
			try {
				$sql = "SELECT 
							owner_id, 
							count(*) count 
						FROM user 
						WHERE date_join >= '$curMonth'
						AND date_join < '$nextMonth'
						AND accept='Y' 
						AND payment_status>=0 
						GROUP BY owner_id";
				$countUserRows = Yii::app()->db->createCommand($sql)->queryAll();
				foreach ($countUserRows as $row) {
					$data[$row['owner_id']] = array(
						'owner_id' => $row['owner_id'],
						'joinmb' => $row['count']
					);
				}
				
				$sql = "SELECT 
							h.owner_id, 
							sum(h.amount) amount,
							count(*) num
						FROM first_order f, order_history h
						WHERE f.order_id=h.order_id
						AND h.verifydate >= '$curMonth'
						AND h.verifydate < '$nextMonth'
						AND h.verify_status=1
						AND f.payment_status>=0
						GROUP BY owner_id";
				$countOrderRows = Yii::app()->db->createCommand($sql)->queryAll();
				
				foreach ($countOrderRows as $row) {
					$d = array(
						'firstordernum' => $row['num'],
						'firstorderamount' => $row['amount'],
					);
					$data[$row['owner_id']] += $d;
				}
				
				foreach ($data as $row) {
					//计算哪种佣金模式钱更多，自动为加盟账号选择多的那个
					$c1 = QpidBalance::countPerFirstOrder(floatval($row['firstorderamount']), intval($row['joinmb']));
					$c2 = QpidBalance::countPerLead($row['owner_id'], intval($row['joinmb']));
					$d = array();
					if ($c1 > $c2) {
						$d['program'] = 'per first order';
						$d['total_earn'] = $c1;
					} else {
						$d['program'] = 'per valid member';
						$d['total_earn'] = $c2;
					}
					$report = new MonthReport();
					$report->attributes = $row + $d;
					$report->payment_id = 0;
					$report->adddate = date('Y-m-d');
					$report->payment_status = 0;
					$report->month = $curMonth;
					$report->save();
					
					//根据月报表重新计算会员的佣金余额
					$owner = Owner::model()->find("loginid='{$report->owner_id}'");
					$owner->balance += $report->total_earn;
					$owner->save();
				}
				
				$trans->commit();
			} catch (Exception $e) {
				$trans->rollback();
			}
			$this->redirect(array('payment/monthReportDetail', 'month' => $_GET['year'].'-'.$_GET['month']));
			exit;
		}
	}
}